<template>
  <div v-if="markdown !== undefined">
    <el-divider>
      <el-link
        @click="switchMd"
        :underline="false"
        :icon="showMd ? CaretTop : CaretBottom"
      >
        Markdown文件
      </el-link>
    </el-divider>
    <div v-show="showMd" v-html="compiledMarkdown" class="markdown"></div>
  </div>
</template>

<script setup lang="ts">
import { useRoute } from "vue-router";
import { ref, watch, onMounted } from "vue";
import { marked } from "marked";
import { CaretTop, CaretBottom } from "@element-plus/icons-vue";

const showMd = ref(true);
const markdown = ref();
const compiledMarkdown = ref();
const route = useRoute();

const switchMd = () => {
  showMd.value = !showMd.value;
};

markdown.value = route.meta.markdown;

// 设置 marked 的渲染器以支持代码高亮
marked.setOptions({
  renderer: new marked.Renderer(),
  breaks: true, // 将换行符转换为 <br> 标签
  pedantic: false,
  gfm: true // 启用 GitHub Flavored Markdown
});

const getMarkdown = async (mdfile: string) => {
  const response = await fetch(mdfile);
  if (response.ok) {
    const content = await response.text(); // 读取文件内容
    compiledMarkdown.value = marked.parse(content);
  } else {
    console.error("无法加载 Markdown 文件");
  }
};

onMounted(async () => {
  markdown.value = route.meta.markdown;
  if (route.meta.markdown !== undefined) {
    getMarkdown(route.meta.markdown as string);
  }
});

watch(
  () => route.path,
  () => {
    markdown.value = route.meta.markdown;
    if (route.meta.markdown !== undefined) {
      getMarkdown(route.meta.markdown as string);
    }
  },
  {
    deep: true
  }
);
</script>

<style scoped>
.markdown {
  text-align: left; /* 设置文本居左 */
}
</style>
